<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Notifications\Notifiable;
use Illuminate\Pagination\LengthAwarePaginator;

class Student extends Model
{
    use HasFactory, Notifiable;

    /**
     * @var string
     */
    public $table = 'student';

    /**
     * @return HasOne
     */
    public function student_class()
    {
        return $this->belongsTo(StudentClass::class, 'student_class_id');
    }

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'student_name',
        'sex',
        'student_class_id',
    ];

    const SIX_MALE = 1;//男
    const SIX_GIRL = 2;//女
    const SIX_STR = '1, 2';

    /**
     * 学生列表
     * @param $params
     * @return mixed
     */
    public function getList($params)
    {
        $student = $this->with('student_class');

        if (!empty($params['student_name'])) {
            $student->where('student_name', 'like', '%'.$params['student_name'].'%');
        }

        if (!empty($params['sex'])) {
            $student->where('sex',  $params['sex']);
        }

        if (!empty($params['student_class_name'])) {
            $student = $student->whereHas(
                'student_class', function ($query) use ($params) {
                $query->where('student_class_name', 'like', '%' . $params['student_class_name'] . '%');
            });
        }
        return $student->paginate(15);
    }

    /**
     * 学生添加
     * @param $data
     * @return bool
     */
    public function add($data)
    {
        $this->student_name = $data['student_name'];
        $this->sex = $data['sex'];
        $this->student_class_id = $data['student_class_id'];
        return $this->save();
    }

    /**
     * 学生删除
     * @param $id
     * @return bool
     */
    public function del($id)
    {
        return $this->where('id', $id)->delete();
    }

    /**
     * 学生修改
     * @param $data
     * @return mixed
     */
    public function edit($data)
    {
        $id = $data['id'];
        unset($data['id']);
        return $this->where('id', $id)->update($data);
    }

    /**
     * 查询单个学生
     * @param $id
     * @return mixed
     */
    public function get($id)
    {
        return $this->with('student_class')->findOrFail($id);
    }
}
